<script setup lang="ts">
	import config from '@/config/index'
	import { onLaunch, onHide } from '@dcloudio/uni-app'
	import { useImStoreToRefs } from '@/store/useImStore'
	import { ImServerClass, uniPushIm } from '@/hooks/useIm/index'
	import { useUserStoreToRefs } from '@/store/useUserStore'
	import { initSubcrib } from '@/hooks/useMessageSubscrib'
	const { userInfo, shareRefereeId, shareStudioId } = useUserStoreToRefs()
	//获取全局对象-imServer
	const { imServer, messagePoint } = useImStoreToRefs()
	onLaunch((options) => {
		console.log("options", options)
		//目前只有用户正式端才需要接收unipush推送
		if(config.beginning == "user" && config.env == "prod"){
			uniPushIm()
		}
		// #ifdef APP-PLUS
		// 锁定屏幕方向
		plus.screen.lockOrientation('portrait-primary');
		maintenanceSwitch()
		// #endif
		initSubcrib()
		shareRefereeId.value = ""
		shareStudioId.value = ""
		//将初始化的im对象缓存到全局对象imServer中
		imServer.value = new ImServerClass()
		if (userInfo.value) {
			imServer.value.login().then((success) => {
				console.log('success', success)
				if (success) {
					getMessagePoint()
					imServer.value.listen((data) => {
						let pages = getCurrentPages()
						let currentPage = pages[pages.length - 1]
						if (data.type == 'onTextMessage' || data.type == 'onImageMessage' || data.type == 'onVideoMessage') {
							// 全局监听文本和图片消息,触发对应页面接口的更新
							switch (currentPage.route) {
								case 'pages/message/index':
								case 'pages/myStudio/index/index':
									uni.$emit("onChatUserList", data)
									break;
								case 'pages/im/message/index':
									uni.$emit("onChatContent", data)
									break;
							}

						}
					})
				}
			})
		}
	})
	const getMessagePoint = () => {
		imServer.value.getServerConversations((res) => {
			let num = 0
			res.data.conversations.forEach((item) => {
				num += item.unReadCount
			});
			messagePoint.value = num
			// #ifdef APP-PLUS
			plus.runtime.setBadgeNumber(messagePoint.value)
			// #endif
		})
	}
	// 系统维护检测
	const maintenanceSwitch = ()=>{
		uniCloud
			.callFunction({
				name: 'systemMaintenance'
			})
			.then((res) => {
				console.log("systemMaintenance",res.result.maintenance)
				// 根据设定的时间检测维护状态，启维护则跳转到维护页告知用户
				setTimeout(()=>{
					maintenanceSwitch()
				},res.result.maintenanceTime)
				if(res.result.maintenance){
					const pages = getCurrentPages()
					const currentPage = pages[pages.length - 1]
					const currentRoute = currentPage.route
					if(currentRoute !== 'pages/login/maintenance'){
						uni.reLaunch({
							url:'/pages/login/maintenance'
						})
					}
					
				}
			})
	}
</script>

<style lang="scss">
	@import '@/styles/index.scss';
</style>